package com.voxel.sense.infomsg.module.home;

import android.app.AlarmManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.nearby.NearbySearch;
import com.example.com.common.app.PresenterFragment;
import com.example.com.common.utils.L;
import com.example.com.common.view.bgabanner.BGABanner;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.IDialog;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.module.firm.FirmListInfoActivity;
import com.voxel.sense.infomsg.module.firm.details.FirmInfoDetailActivity;
import com.voxel.sense.infomsg.module.map.monitor.baseInfo.MonitorMapActivity;
import com.voxel.sense.infomsg.module.map.warn.FirmWarnActivity;
import com.voxel.sense.infomsg.module.task.list.TaskListActivity;
import com.voxel.sense.infomsg.module.user.staff.StaffListActivity;
import com.voxel.sense.infomsg.module.wifi.WifiWarnActivity;
import com.voxel.sense.infomsg.utils.BadgeUtil;
import com.voxel.sense.infomsg.utils.GlideImageLoader;
import com.voxel.sense.infomsg.utils.marker.cluster.data.RegionItem;
import com.voxel.sense.infomsg.utils.marker.cluster.strategy.FirmBeanConvertStrategy;
import com.voxel.sense.infomsg.widget.map.utils.MarkerManageUtils;
import com.voxel.sense.infomsg.widget.map.utils.OnCtmMarkerClickListener;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.AccordionTransformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.FirmLocationEntity;
import cyy.example.com.facotry.share.SPEngine;

/**
 * Created by chenyiyao on 2017/10/27.
 */

public class HomeFrag extends PresenterFragment<HomeContract.Presenter> implements BGABanner.Delegate
        , HomeContract.View<List<FirmLocationEntity>> {

    @BindView(R.id.ll_resource_info)
    LinearLayout ll_resource_info; //污染信息
    @BindView(R.id.ll_firm_misson)
    LinearLayout ll_firm_misson; //企业填报
    @BindView(R.id.ll_firm_warn)
    LinearLayout ll_firm_monitor; //实时监控
    @BindView(R.id.ll_warn_manager)
    LinearLayout ll_warn_manager; //应急执法
    @BindView(R.id.wifi_count)
    TextView wifiWarnCount;    //断网警告
    @BindView(R.id.banner)
    Banner banner;//轮播图
    @BindView(R.id.btn_search_left)
    Button btn_search_left; //城市列表
    @BindView(R.id.view_search)
    TextView tv_search; //顶部查询
    @BindView(R.id.title_btn_right)
    ImageButton btn_right; //顶部查询
    @BindView(R.id.view_shield)
    View view_shield; //界面蒙版
    @BindView(R.id.warn_count)
    TextView mWarnCount;

    FirmLocationEntity mFirmentities;//获取当前所有公司的实体
    private AMap aMap;
    //定位需要的声明

    private String mSelectCity = "河源市";//城市选中列表，选中的城市，默认深圳
    private int mLocationFreshTime = 1000 * 10;//地图定位回调刷新时间
    private PopupWindow mPopupWindow;//打卡popWin

    MarkerManageUtils mMarkerManage;

    private int warnCounts = 0;
    private int wifiWarnCounts = 0;

    @Override
    protected HomeContract.Presenter initPresenter() {
        return new HomePresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.frag_home;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if (aMap == null) {
            aMap = ((SupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            //移动地图中心点
            aMap.moveCamera(CameraUpdateFactory.
                    changeLatLng(new LatLng(Constants.latitude, Constants.longitude)));
            aMap.moveCamera(CameraUpdateFactory.zoomTo(13f));
        }
        return mRoot;
    }


    @Override
    public void onResume() {
        super.onResume();
//        aMap.moveCamera(CameraUpdateFactory.
//          changeLatLng(new LatLng(114.665524, 23.653317)));
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        NearbySearch.destroy();
        if (timer != null) {
            timer.cancel();
        }
    }


    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        initPopWindow();
        String regionCode = SPEngine.getSPEngine().getUserInfo().getRegionCode();

    }


    @Override
    protected void initData() {
        super.initData();
        btn_search_left.setText(mSelectCity);
        initMap();
        //加载公司的位置信息
        mPresenter.LoadMarkerInfo();
        //加载轮播图
        mPresenter.loadBannerData();


        //获取警告条数
        showTimeWarn();


    }

    Timer timer;
    private static final long TIME_MILLS = 2 * 60 * 1000L;

    private void showTimeWarn() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mPresenter.getWarnCount();
                mPresenter.getWifiWarnCount();
            }
        }, 0, TIME_MILLS);
    }


    private void initMap() {
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(true);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        //定位的小图标 默认是蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        //连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        myLocationStyle.interval(mLocationFreshTime);
        //十五秒定位一次
        aMap.setMyLocationStyle(myLocationStyle);
        //设置缩放级别
//        aMap.setMinZoomLevel(Constants.MAP_MIN_ZOOM_LEVEL);
        aMap.setMaxZoomLevel(Constants.MAP_MAX_ZOOM_LEVEL);

        //地图自身的定位按钮定位的回调
        aMap.setOnMyLocationChangeListener(mPresenter.getMyLocationChangeListener());

        mMarkerManage = new MarkerManageUtils(aMap);
        //marker点击事件
        mMarkerManage.setMarkerClickListener(new OnCtmMarkerClickListener<RegionItem<FirmLocationEntity>>() {
            @Override
            public boolean onNoClusterClick(Marker marker, RegionItem<FirmLocationEntity> entity) {
                double latitude = aMap.getCameraPosition().target.latitude;
                double longitude = aMap.getCameraPosition().target.longitude;
//                MonitorMapActivity.show(HomeFrag.this.getContext(),
//                        mPresenter.getFirmDataList(), latitude, longitude);
                FirmInfoDetailActivity.show(HomeFrag.this.getContext(), null, entity.getObject().getCompanyId());
                return false;
            }

            @Override
            public boolean onClusterClick(Marker marker) {
                return false;
            }
        });
        Log.e("+++++", " /// " + aMap.getMaxZoomLevel());

    }

    //污染资源
    @OnClick({R.id.ll_resource_info, R.id.ll_warn_manager, R.id.ll_firm_misson, R.id.ll_bm_staff,
            R.id.view_search, R.id.btn_search_left, R.id.ll_firm_warn, R.id.title_btn_right})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_resource_info:
                //污染源信息
                FirmListInfoActivity.show(getContext(), mSelectCity);
                break;
            case R.id.ll_warn_manager:
                //任务管理
//                TaskManagerActivity.show(getActivity());
//                TaskListActivity.show(getActivity());
                WifiWarnActivity.show(getActivity());
                break;
            case R.id.ll_firm_misson:
                //实时监控
                double latitude = aMap.getCameraPosition().target.latitude;
                double longitude = aMap.getCameraPosition().target.longitude;
                MonitorMapActivity.show(getContext(), mPresenter.getFirmDataList(), latitude, longitude);
                break;
            case R.id.ll_firm_warn:
                //突发预警
                double latitude1 = aMap.getCameraPosition().target.latitude;
                double longitude1 = aMap.getCameraPosition().target.longitude;
                FirmWarnActivity.show(getContext(), mFirmentities, latitude1, longitude1);
                break;
            case R.id.view_search:
                //搜索按钮
                SearchActivity.show(getContext());
                break;
            case R.id.ll_bm_staff:
                //人员列表
                StaffListActivity.show(getContext());
                break;
            case R.id.btn_search_left:
                //搜索栏左边按钮
                btn_search_left.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null,
                        getResources().getDrawable(R.mipmap.ic_drop_selected_icon), null);
                break;
            case R.id.title_btn_right:
                //右侧功能按钮
                mPresenter.doClockIn();
//                int yoff = SizeUtils.dp2px(10);
//                mPopupWindow.showAsDropDown(btn_right, 0, -yoff);
//                view_shield.setVisibility(View.VISIBLE);

//                IDialog.getInstance().showMessageDialog(getContext(), "公告", "系统主要用于监管企业的污染源信息", new DialogCallBack() {
//                    @Override
//                    public void onClick(int what) {
//                    }
//                });
                break;
        }
    }

    private void initPopWindow() {
        View inflate = getLayoutInflater().inflate(R.layout.layout_pulldown_main, null);
        mPopupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setOutsideTouchable(true);

        initPopWinEvent(inflate);
    }

    private void initPopWinEvent(View inflate) {
        //通知点击事件
        inflate.findViewById(R.id.tv_notice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IDialog.getInstance().showMessageDialog(getContext(), "公告", "系统主要用于监管企业的污染源信息", new DialogCallBack() {
                    @Override
                    public void onClick(int what) {
                    }
                });
            }
        });
        initClockInEvent(inflate);


        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_shield.setVisibility(View.GONE);
            }
        });
    }

    //设置打卡事件
    private void initClockInEvent(View inflate) {
        //打卡事件 清单
        inflate.findViewById(R.id.tv_clock_in).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mPresenter.doClockIn();
            }
        });
    }

    //污染资源
    //轮播图点击事件
    @Override
    public void onBannerItemClick(BGABanner banner, View view, Object model, int position) {
    }

    @Subscribe
    public void onEvent(EventEntity event) {
        switch (event.key) {
            case EventBusConstants.QUERY_CONFIG:
                if (event.value.equals(EventBusConstants.SUCCEED)) {
                }
                break;
            case EventBusConstants.LOCATION_UP_FLAG:
                boolean f = (boolean) event.value;
                mPresenter.changeUpCondition(f);
                break;
        }
    }

    @Override
    public AMap getMap() {
        return aMap;
    }

    @Override
    public void RefreshPointCity(String str) {
        btn_search_left.setText(str);
    }

    @Override
    public void RefreshMapCamera(double latitude, double longititude) {
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(latitude, longititude)));
    }

    @Override
    public void initMarker(ArrayList<MarkerOptions> markerOptions) {
        aMap.clear(true);//true保持定位信息，false清楚定位信息
        //传入true时，会改变地图状态，根据marker转移中心点，这里的中心保持定位位置，需要为false
        aMap.addMarkers(markerOptions, false);
    }

    @Override
    public void onShowtMarker(List<FirmLocationEntity> markerData) {
//        List<ClusterItem> clusterItems = ConvertStrategy.convertEntity(markerData, Constants.MARKER_TYPE_NO_INFO);
        aMap.moveCamera(CameraUpdateFactory.
                changeLatLng(new LatLng(23.640153, 114.665524)));
        FirmBeanConvertStrategy strategy = new FirmBeanConvertStrategy();
        mMarkerManage.addMarkers(markerData, Constants.MARKER_TYPE_NO_INFO, strategy);
    }

    @Override
    public String getCurrentciity(String city) {
        if (btn_search_left != null) {
            return btn_search_left.getText().toString();
        }
        return null;
    }

    @Override
    public void setBannerDatas(List list) {
        banner.setImages(list)
                .setImageLoader(new GlideImageLoader())
                .setBannerAnimation(AccordionTransformer.class)
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        L.d("你点击了：" + position);
                    }
                })
                .start();
    }

    @Override
    public void onClickInSuccess() {
        if (mPopupWindow != null && mPopupWindow.isShowing())
            mPopupWindow.dismiss();
    }

    private static int badgeCount;

    @Override
    public void setWarinCount(int count) {
        mWarnCount.setText(count + "");
        warnCounts = count;
        EventBus.getDefault().post(new EventEntity(EventBusConstants.HOME_BADGE_COUNT, wifiWarnCounts+warnCounts));
        BadgeUtil.setBadgeCount(getContext(), wifiWarnCounts+warnCounts, R.drawable.sp_warn_count_bg);
    }

    @Override
    public void setWifiWarnCount(String count) {
        wifiWarnCount.setText(count + "");
        wifiWarnCount.setTextColor(Color.WHITE);
        wifiWarnCounts = Integer.valueOf(count);
        EventBus.getDefault().post(new EventEntity(EventBusConstants.HOME_BADGE_COUNT, wifiWarnCounts+warnCounts));
        BadgeUtil.setBadgeCount(getContext(), wifiWarnCounts+warnCounts, R.drawable.sp_warn_count_bg);
    }

}